<?php
namespace app\admin\controller;
use think\Controller;
use think\Request;
use think\db;
vendor('Qiniu.autoload');
use Qiniu\Auth as Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

class Common extends Controller
{

    public function _initialize()
    {
        Cfg();      //全局变量加载
        if(!session('aid_admin.id')){
            $this->redirect('Login/index');
        }
        $request = Request::instance();
        $path = strtolower($request->controller().'/'.$request->action());
        $this->assign('path',$path);
//        dump($path);
    }

    /**
     * 图片上传
     * @return String 图片的完整URL
     */
    public function uploadTicketFile()
    {
        if(request()->isPost()){
            $file = request()->file('file');
            // 要上传图片的本地路径
            $filePath = $file->getRealPath();
            $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
            // 上传到七牛后保存的文件名
            $key =substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
            // 需要填写你的 Access Key 和 Secret Key
            $accessKey = config('qiniu.accessKey');
            $secretKey = config('qiniu.secretKey');

            // 构建鉴权对象
            $auth = new Auth($accessKey, $secretKey);
            // 要上传的空间
            $bucket = config('qiniu.bucket');
            $domain = config('qiniu.domain');
            $token = $auth->uploadToken($bucket);
            // 初始化 UploadManager 对象并进行文件的上传
            $uploadMgr = new UploadManager();
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
            if ($err !== null) {
                echo ["err"=>1,"msg"=>$err,"data"=>""];
            } else {
                //返回图片的完整URL
                return  json(['code'=>1,'msg'=>'上传成功','imgUrl'=>'http://'.$domain.'/'.$ret['key']]);
        }
        }
    }


}